<template>
  <view class="container  page-bg">
    <view class="p-2">
      <view class="my-2 text-right mb-3" @click="onReset">
        <text class="font32">恢复默认设置</text>
      </view>
      <view v-for="(item,index) in gameList" :key="index + (settingFlag ? '-refresh' : '')"
            class="bg-fff p-2 rounded20 mb-2 d-flex d-flex-between d-flex-middle">
        <view class="d-flex">
          <image
              :src="item.icon"
              mode="widthFix" class="img mr-2"></image>
          <text class="font26">{{ item.name }}</text>
        </view>
        <view class="">
          <switch :checked="item.is_open" @change="onSwitch($event,item.id)" color="#598dfc"
                  style="transform:scale(0.6)"/>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import {
  mapState
} from "vuex"
import {
  fileApi
} from "@/http/fileApi.js";
import store from '@/store/index.js';
export default {
  data() {
    return {
      gameList: [],
      settingFlag: false
    }
  },
  computed: {
    ...mapState({
      loginState: state => state.loginState,
    })
  },
  onLoad() {
    this.game()
  },
  methods: {
    async game() {
      let res = await fileApi.getGameList()
      this.gameList = res
    },
    async onReset() {
      let that = this
      store.commit('setHomeSettingFlag', true)
      uni.showModal({
        title: '提示',
        content: '确定要恢复默认设置吗？',
        success: async function (res) {
          if (res.confirm) {
            try {
              await fileApi.gameDefault(); // 调用恢复默认设置的API
              // 切换flag并重新加载数据
              that.settingFlag = !that.settingFlag;
              await that.game(); // 重新获取游戏列表

              uni.showToast({
                title: '已恢复默认设置',
                icon: 'success'
              });
            } catch (error) {
              uni.showToast({
                title: '恢复失败',
                icon: 'none'
              });
            }
          } else if (res.cancel) {
            // 用户取消操作，无需处理
          }
        }
      })
    },
    async onSwitch(event, id) {
      store.commit('setHomeSettingFlag', true)
      if (!event.detail.value) {
        await fileApi.gameClose({
          id: id,
        })
      } else {
        await fileApi.gameOpen({
          id: id,
        })
      }
    },
    goUrl(urlPages) {
      if (!this.loginState) {
        uni.showToast({
          title: '未登录，请先登录！',
          icon: 'none'
        })
        setTimeout(() => {
          uni.navigateTo({
            url: '/pages/login/login'
          })
        }, 1500)
      } else {
        uni.navigateTo({
          url: urlPages
        })
      }
    },
  },

}
</script>

<style scoped>
.container {
  position: relative;
}


.img {
  height: 80rpx;
  width: 80rpx;
}


input {
  flex: 1;
  height: 80rpx;
  font-size: 28rpx;
}


</style>